<template>
  <div class="app-container attribute-manager">
    <!-- 页面标题与描述 -->
    <div class="page-header">
      <div class="header-title">
        <i class="el-icon-collection-tag header-icon"></i>
        <span>商品属性管理</span>
      </div>
      <!-- <div class="header-description">管理商品的可选属性，用于商品详情和筛选</div> -->
    </div>

    <!-- 搜索表单 -->
    <el-card shadow="hover" class="filter-container">
      <el-form ref="queryForm" :model="queryParams" size="small" :inline="true">
        <el-form-item label="属性名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入属性名称"
            clearable
            prefix-icon="el-icon-search"
            class="enhanced-input"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="属性类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="请选择属性类型" clearable class="enhanced-input">
            <el-option 
              v-for="item in typeOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value">
              <i :class="getTypeIcon(item.value)"></i>
              <span style="margin-left: 8px">{{ item.label }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" class="enhanced-button" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" class="enhanced-button" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8 toolbar-container">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['business:attribute:add']"
          type="primary"
          icon="el-icon-plus"
          class="primary-button"
          @click="handleAdd"
        >新增属性</el-button>
      </el-col>
      <right-toolbar @queryTable="getList" />
    </el-row>

    <!-- 数据表格 -->
    <el-card shadow="hover" class="table-container">
      <el-table v-loading="loading" :data="attributeList" border :header-cell-style="{ background: '#f5f7fa' }">
        <el-table-column label="#" type="index" width="60" align="center" />
        <el-table-column label="属性名称" prop="name" min-width="180">
          <template slot-scope="scope">
            <div class="attribute-name">
              <i :class="getTypeIcon(scope.row.type)" class="attribute-icon"></i>
              <el-tooltip :content="scope.row.name" placement="top">
                <span>{{ scope.row.name }}</span>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="属性类型" align="center" width="120">
          <template slot-scope="scope">
            <el-tag 
              :type="getTypeTag(scope.row.type)" 
              effect="plain"
              size="medium"
            >
              {{ typeMap[scope.row.type] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="选项值" prop="options" min-width="280">
          <template slot-scope="scope">
            <div v-if="[3, 4].includes(scope.row.type) && scope.row.options">
              <el-tag
                v-for="(option, index) in parseOptions(scope.row.options)"
                :key="index"
                :type="getRandomTagType(index)"
                class="option-tag"
                size="small"
              >
                {{ option }}
              </el-tag>
            </div>
            <span v-else class="muted-text">{{ getTypePlaceholder(scope.row.type) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center" class-name="operation-column">
          <template slot-scope="scope">
            <el-button
              v-hasPermi="['business:attribute:edit']"
              size="mini"
              type="primary"
              icon="el-icon-edit"
              circle
              plain
              @click="handleUpdate(scope.row)"
            ></el-button>
            <el-button
              v-hasPermi="['business:attribute:remove']"
              size="mini"
              type="danger"
              icon="el-icon-delete"
              circle
              plain
              @click="handleDelete(scope.row)"
            ></el-button>
            <el-tooltip content="查看详情" placement="top">
              <el-button
                size="mini"
                type="info"
                icon="el-icon-view"
                circle
                plain
                @click="viewDetails(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 新增/修改弹窗 -->
    <el-dialog 
      :title="title" 
      :visible.sync="open" 
      width="600px" 
      :close-on-click-modal="false"
      class="attribute-dialog"
    >
      <div class="dialog-content">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="属性名称" prop="name">
            <el-input 
              v-model="form.name" 
              placeholder="请输入唯一属性名称" 
              class="enhanced-input"
            />
          </el-form-item>

          <el-form-item label="属性类型" prop="type">
            <el-select 
              v-model="form.type" 
              placeholder="请选择属性类型"
              class="enhanced-input"
            >
              <el-option
                v-for="item in typeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
                <i :class="getTypeIcon(item.value)"></i>
                <span style="margin-left: 8px">{{ item.label }}</span>
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            v-if="[3,4].includes(form.type)"
            key="options-input"
            label="选项值"
            prop="options"
          >
            <div class="option-hint">
              <i class="el-icon-info"></i>
              <span>{{ form.type === 3 ? '单选项：用户只能选择一个选项' : '多选项：用户可以选择多个选项' }}</span>
            </div>
            <el-table :data="optionItems" border class="option-table">
              <el-table-column prop="value" label="选项值">
                <template slot-scope="scope">
                  <el-input 
                    v-model="scope.row.value" 
                    placeholder="请输入选项值" 
                    class="enhanced-input"
                  />
                </template>
              </el-table-column>
              <el-table-column width="80">
                <template slot="header">
                  <el-button 
                    icon="el-icon-plus" 
                    size="mini" 
                    type="primary" 
                    plain
                    @click="addOption" 
                  />
                </template>
                <template slot-scope="scope">
                  <el-button
                    icon="el-icon-delete"
                    type="danger"
                    size="mini"
                    plain
                    @click="removeOption(scope.$index)"
                  />
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          
          <el-form-item v-if="form.type === 5" label="日期格式" prop="dateFormat">
            <el-select 
              v-model="form.dateFormat" 
              placeholder="请选择日期格式"
              class="enhanced-input"
            >
              <el-option label="年-月-日" value="yyyy-MM-dd" />
              <el-option label="年-月-日 时:分:秒" value="yyyy-MM-dd HH:mm:ss" />
              <el-option label="年月日" value="yyyyMMdd" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel" class="cancel-button">取 消</el-button>
        <el-button type="primary" @click="submitForm" class="submit-button">确 定</el-button>
      </div>
    </el-dialog>
    
    <!-- 属性详情查看弹窗 -->
    <el-dialog
      title="属性详情"
      :visible.sync="detailsVisible"
      width="500px"
      class="details-dialog"
    >
      <div v-if="currentAttribute" class="attribute-details">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="属性名称">
            {{ currentAttribute.name }}
          </el-descriptions-item>
          <el-descriptions-item label="属性类型">
            <el-tag :type="getTypeTag(currentAttribute.type)">
              {{ typeMap[currentAttribute.type] }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item v-if="[3, 4].includes(currentAttribute.type)" label="选项值">
            <div class="option-tags">
              <el-tag
                v-for="(option, index) in parseOptions(currentAttribute.options)"
                :key="index"
                :type="getRandomTagType(index)"
                class="option-tag"
              >
                {{ option }}
              </el-tag>
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ currentAttribute.createTime || '未知' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAttribute, addAttribute, updateAttribute, delAttribute } from '@/api/business/attribute'

export default {
  name: 'ProductAttribute',
  data() {
    return {
      loading: false,
      attributeList: [],
      open: false,
      detailsVisible: false,
      currentAttribute: null,
      title: '',
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        type: null
      },
      form: {
        id: null,
        name: '',
        type: null,
        options: null,
        dateFormat: 'yyyy-MM-dd'
      },
      rules: {
        name: [{ required: true, message: '属性名称不能为空', trigger: 'blur' }],
        type: [{ required: true, message: '请选择属性类型', trigger: 'change' }]
      },
      typeOptions: [
        { value: 1, label: '文本' },
        // { value: 2, label: '数字' },
        { value: 3, label: '单选' }
        // { value: 4, label: '多选' },
        // { value: 5, label: '日期' }
      ],
      typeMap: {
        1: '文本',
        // 2: '数字',
        3: '单选'
        // 4: '多选',
        // 5: '日期'
      },
      optionItems: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getTypeIcon(type) {
      const iconMap = {
        1: 'el-icon-edit-outline',
        2: 'el-icon-odometer',
        3: 'el-icon-finished',
        4: 'el-icon-document-checked',
        5: 'el-icon-date'
      }
      return iconMap[type] || 'el-icon-collection-tag'
    },
    getTypeTag(type) {
      const tagMap = {
        1: '',
        2: 'info',
        3: 'success',
        4: 'warning',
        5: 'primary'
      }
      return tagMap[type] || ''
    },
    getTypePlaceholder(type) {
      const placeholderMap = {
        1: '文本类型 - 用户可自由输入',
        2: '数字类型 - 用户输入数值',
        5: '日期类型 - 用户选择日期'
      }
      return placeholderMap[type] || '无选项值'
    },
    getRandomTagType(index) {
      const types = ['', 'success', 'info', 'warning', 'danger']
      return types[index % types.length]
    },
    parseOptions(options) {
      try {
        return JSON.parse(options)
      } catch (e) {
        return []
      }
    },
    viewDetails(row) {
      this.currentAttribute = row
      this.detailsVisible = true
    },
    handleDelete(row) {
      // 确保传入的是一个数组，并且将id转换为Long类型
      const id = parseInt(row.id)
      if (!isNaN(id)) {
        this.$confirm('确定要删除该属性吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 确保传入的是一个数组，并且将id转换为Long类型
          delAttribute([id]).then(res => {
            this.$modal.msgSuccess('删除成功')
            this.getList()
            this.open = false
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      } else {
        // 打印错误信息，方便调试
        console.error('无效的ID类型，无法转换为数字:', row.id)
        this.$modal.msgError('无效的ID类型，请检查数据')
      }
    },
    // 查询列表
    getList() {
      this.loading = true
      listAttribute(this.queryParams).then(res => {
        this.attributeList = res.rows || []
        this.total = res.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },

    // 搜索按钮操作
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    // 重置按钮操作
    resetQuery() {
      this.$refs.queryForm.resetFields()
      this.handleQuery()
    },

    // 表单重置
    resetForm() {
      this.form = {
        id: null,
        name: '',
        type: null,
        options: null,
        dateFormat: 'yyyy-MM-dd'
      }
      this.optionItems = []
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.resetForm()
    },

    // 新增按钮操作
    handleAdd() {
      this.resetForm()
      this.open = true
      this.title = '新增商品属性'
    },

    // 修改按钮操作
    handleUpdate(row) {
      this.resetForm()
      this.form = { ...row }
      if (row.options) {
        try {
          this.optionItems = JSON.parse(row.options).map(v => ({ value: v }))
        } catch (e) {
          this.optionItems = []
        }
      }
      this.open = true
      this.title = '修改商品属性'
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          // 处理选项值
          if ([3, 4].includes(this.form.type)) {
            const validOptions = this.optionItems.filter(item => item.value.trim() !== '')
            if (validOptions.length === 0) {
              this.$message.warning('请至少添加一个有效的选项值')
              return
            }
            this.form.options = JSON.stringify(validOptions.map(i => i.value.trim()))
          } else {
            this.form.options = null
          }

          if (this.form.id) {
            updateAttribute(this.form).then(() => {
              this.$modal.msgSuccess('修改成功')
              this.getList()
              this.open = false
            })
          } else {
            addAttribute(this.form).then(() => {
              this.$modal.msgSuccess('新增成功')
              this.getList()
              this.open = false
            })
          }
        }
      })
    },
    addOption() {
      this.optionItems.push({ value: '' })
    },
    removeOption(index) {
      this.optionItems.splice(index, 1)
    }
  }
}
</script>

<style lang="scss" scoped>
.attribute-manager {
  .page-header {
    margin-bottom: 20px;
    .header-title {
      font-size: 20px;
      font-weight: 600;
      color: #303133;
      margin-bottom: 8px;
      display: flex;
      align-items: center;
      
      .header-icon {
        font-size: 24px;
        margin-right: 10px;
        color: #409EFF;
      }
    }
    
    .header-description {
      font-size: 14px;
      color: #606266;
    }
  }
  
  .filter-container {
    margin-bottom: 20px;
    border-radius: 8px;
    
    .enhanced-input {
      width: 240px;
    }
    
    .enhanced-button {
      border-radius: 4px;
      transition: all 0.3s;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0,0,0,0.1);
      }
    }
  }
  
  .toolbar-container {
    margin-bottom: 20px;
    
    .primary-button {
      background: linear-gradient(135deg, #409EFF, #3a8ee6);
      border: none;
      border-radius: 4px;
      transition: all 0.3s;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
      }
    }
  }
  
  .table-container {
    border-radius: 8px;
    margin-bottom: 20px;
    
    .attribute-name {
      display: flex;
      align-items: center;
      
      .attribute-icon {
        color: #409EFF;
        margin-right: 8px;
        font-size: 16px;
      }
    }
    
    .option-tag {
      margin-right: 6px;
      margin-bottom: 6px;
    }
    
    .muted-text {
      color: #909399;
      font-size: 12px;
    }
    
    .operation-column {
      .el-button + .el-button {
        margin-left: 8px;
      }
    }
  }
  
  .attribute-dialog {
    .dialog-content {
      padding: 10px;
      
      .option-hint {
        margin-bottom: 10px;
        font-size: 12px;
        color: #909399;
        display: flex;
        align-items: center;
        
        i {
          margin-right: 5px;
          color: #E6A23C;
        }
      }
      
      .option-table {
        margin-bottom: 10px;
      }
      
      .enhanced-input {
        width: 100%;
      }
    }
    
    .dialog-footer {
      display: flex;
      justify-content: flex-end;
      
      .cancel-button, .submit-button {
        min-width: 90px;
      }
      
      .submit-button {
        background: linear-gradient(135deg, #409EFF, #3a8ee6);
        border: none;
        transition: all 0.3s;
        
        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
        }
      }
    }
  }
  
  .details-dialog {
    .attribute-details {
      padding: 10px;
      
      .option-tags {
        display: flex;
        flex-wrap: wrap;
        
        .option-tag {
          margin-right: 6px;
          margin-bottom: 6px;
        }
      }
    }
  }
}

// 修复深层嵌套组件样式
::v-deep {
  .el-card__header {
    padding: 12px 20px;
    font-weight: 600;
  }
  
  .el-card__body {
    padding: 15px 20px;
  }
  
  .el-table th {
    font-weight: 600;
    color: #303133;
  }
  
  .el-table--border {
    border-radius: 4px;
    overflow: hidden;
  }
  
  .el-tag {
    border-radius: 4px;
  }
  
  .el-form-item__label {
    font-weight: 500;
  }
  
  .el-dialog__header {
    padding: 15px 20px;
    border-bottom: 1px solid #EBEEF5;
  }
  
  .el-dialog__title {
    font-weight: 600;
    color: #303133;
  }
  
  .el-descriptions-item__label {
    font-weight: 500;
  }
}
</style>
